<template>
	<div>
		<!-- xpert导航栏 -->
		<xpertNavBar :statusTab="statusTab" />
		<div style="height: 150px; width: 100%"></div>
		<div class="customize">Customize your order</div>
		<!-- 输入框 -->
		<div class="inpForm">
			<!-- 上面的回显数据 -->
			<div v-if="act == 2" class="topHui">
				<div class="overview">Overview</div>
				<div class="inp">
					<div class="tit">Targeted problem <i>*</i></div>
					<input type="text" v-model="problem" class="inpValue" name="" id="" />
				</div>
				<div class="inp">
					<div class="tit">Description <i>*</i></div>
					<a-textarea class="textarea" :maxlength="200" v-model:value="description" :auto-size="{ minRows: 5, maxRows: 5 }" placeholder="Autosize height based on content lines" />
					<div class="count f f-a-c f-j-b">
						<!-- <span>As your Gig storefront, your title is the most important place to include keywords that buyers would likely use to search for a service like yours.</span> -->
						<!-- <span>0/200 max</span> -->
					</div>
				</div>
			</div>
			<div class="inpTit">Select available time</div>
			<!-- 这个是时间选择 -->
			<div class="time">
				<div class="topTimr f f-j-b">
					<div class="lefTime">
						<Time @ToptMonth="ToptMonth" @dateChange="dateChange" @NextMonth="NextMonth" ref="timeUpload" />
					</div>
					<div class="rigTime">
						<!-- 右边选择 -->
						<Hous ref="hous" />
					</div>
				</div>
				<div class="botSetel">
					<div class="problemTit f f-a-c">Targeted problem <span>*</span></div>
					<el-select v-model="values" @change="changeFn" placeholder="Select" size="large" style="width: 240px">
						<el-option v-for="item in timelist" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</div>
			</div>
			<!-- Select meeting method -->
			<div class="meeting">
				<div class="meetingCount">Select meeting method</div>
				<div class="tuImg f f-a-c f-w-w">
					<img src="/src/assets/user/img2.png" @click="actIMg = 1" :class="{ actBor: actIMg == 1 }" class="img1 hand" alt="" />
					<img src="/src/assets/user/img1.png" @click="actIMg = 2" :class="{ actBor: actIMg == 2 }" class="img1 hand" alt="" />
				</div>
			</div>
			<div class="btns f f-a-c">
				<div @click="goSend" class="btn hand">Send</div>
			</div>
		</div>
		<xpertTabbar />
	</div>
</template>

<script setup>
	import Time from "./Times.vue";
	import Hous from "./hous.vue";
	import { timelist } from "@/utils/setting.js";
	import { ref, reactive, onMounted } from "vue";
	import { ElMessage, dayjs } from "element-plus";
	import { WorkMonth, GetWorkingDays, GetTheTimeYouCanWork, RescheduleTheOrder, AgreeToTheRequestApplication, CreateACustomOrder, CreateOrder } from "@/api/xpert.js";
	import xpertTabbar from "@/components/tabBar/xpertTabbar.vue";
	import xpertNavBar from "@/components/navBar/xpertNavBar.vue";
	import { useRoute } from "vue-router";
	import router from "@/router/index.js";
	import ButtonDiffuse from "@/components/Button/ButtonDiffuse.vue";
	let route = useRoute();
	let problemVal = ref("");
	let actIMg = ref(route.query.meetingType || 1);
	let problem = ref(route.query.descriptionTitle);
	let description = ref(route.query.descriptionDetail);
	let id = route.query.id || 0;
	let orderId = route.query.orderId || 0;
	let userId = route.query.userId || 0;
	let title = route.query.title || 0;
	let count = route.query.count || 0;
	// let meetingType = route.query.meetingType || 0;
	let act = route.query.act || "";
	let value = ref(new Date());
	const calendar = ref("");
	const timeUpload = ref("");
	const statusTab = ref(1);
	const hous = ref("");
	let timeObj = ref({});
	let time = ref("");
	let timNe = ref("");
	let dayTimeList = ref([]);
	const values = ref("30");
	const options = [
		{
			value: "Option1",
			label: "Option1"
		},
		{
			value: "Option2",
			label: "Option2"
		},
		{
			value: "Option3",
			label: "Option3"
		},
		{
			value: "Option4",
			label: "Option4"
		},
		{
			value: "Option5",
			label: "Option5"
		}
	];
	onMounted(async () => {
		await getMoneys();
		window.addEventListener("scroll", handleScroll);
	});
	// ------------------------------------------------------------------------------------------------------
	const goSend = async () => {
		// 创建订单
		if (act == 1) {
			// 年月
			console.log(timNe.value + " " + dayTimeList.value[hous.value.ind].timeStr + ":00", 111111111111);
			console.log(dayTimeList.value[hous.value.ind], 22222222222);
			console.log(values.value, 333333333);
			// return;
			let n = await CreateOrder({
				startTime: timNe.value + " " + dayTimeList.value[hous.value.ind].timeStr + ":00",
				// userIdXp: JSON.parse(localStorage.getItem("logininfo")).userIdXp,
				// userIdXp: userId,
				timeInterval: values.value,
				gigsId: id,
				meetingType: actIMg.value,
				descriptionTitle: title,
				descriptionDetail: count
			});
			if (n.code == 200) {
				// 如果成功后直接跳转成功页面
				ElMessage.success(n.msg);
				setTimeout(() => {
					// router.replace({
					// 	path: "/UseCustomizeOrderEnder"
					// });
					router.go(-1);
				}, 1000);
			}
		} else if (act == 2) {
			// return;
			let n = await CreateACustomOrder({
				startTime: timNe.value + " " + dayTimeList.value[hous.value.ind].timeStr + ":00",
				timeInterval: values.value,
				sellerUserId: userId,
				meetingType: actIMg.value,
				descriptionTitle: problem.value,
				descriptionDetail: description.value
			});
			if (n.code == 200) {
				// 如果成功后直接跳转成功页面
				ElMessage.success(n.msg);
				setTimeout(() => {
					// router.replace({
					// 	path: "/UseCustomizeOrderEnder"
					// });
					router.go(-1);
				}, 1000);
			}
		} else if (act == 3) {
			let n = await RescheduleTheOrder({
				startTime: timNe.value + " " + dayTimeList.value[hous.value.ind].timeStr + ":00",
				// userIdXp: JSON.parse(localStorage.getItem("logininfo")).userIdXp,
				// userIdXp: userId,
				timeInterval: values.value,
				orderId: orderId,
				meetingType: actIMg.value,
				descriptionTitle: problem.value,
				descriptionDetail: description.value
			});
			if (n.code == 200) {
				// 如果成功后直接跳转成功页面
				ElMessage.success(n.msg);
				setTimeout(() => {
					// router.replace({
					// 	path: "/UseCustomizeOrderEnder"
					// });
					router.go(-1);
				}, 1000);
			}
		}
	};
	// 获取工作时间
	const GetWorkingTime = async day => {
		let n = await GetTheTimeYouCanWork({
			// userIdXp: JSON.parse(localStorage.getItem("logininfo")).userIdXp,
			userIdXp: userId,
			year: day.split("/")[0],
			month: day.split("/")[1],
			day: day.split("/")[2],
			workMinute: values.value
		});
		dayTimeList.value = n.data;
		hous.value.list = n.data;
		hous.value.ind = n.data.findIndex(obj => obj.workStatus == true); //workStatus
	};
	// 点击日期
	const dateChange = obj => {
		console.log(obj, "22222");
		let time = extractDate(obj.format);
		// 调取获取时间
		timNe.value = time;
		GetWorkingTime(time);
	};
	// 切换时间
	const changeFn = val => {
		console.log(val, "454545454545");
		GetWorkingTime(timNe.value);
	};
	// 这个是获取可工作的月份
	const getMoneys = async () => {
		let n = await WorkMonth({
			// userId: JSON.parse(localStorage.getItem("logininfo")).userIdXp
			userId: userId
		});
		timeObj.value = n.data;
		// 这个是获取可工作的月份
		time.value = n.data.startMonth;
		timeUpload.value.mony = generateMonthArray(n.data);
		// console.log(resultArray, "121212");
		yarnDay();
	};
	// 提取年月日
	function extractDate(dateString) {
		var formattedDate = dateString.replace("年", "/").replace("月", "/").replace("日", "");
		return formattedDate;
	}
	// 获取可工作的天数
	const yarnDay = async () => {
		// console.log(time.value, "33333333333333");
		let n = await GetWorkingDays({
			year: time.value.split("/")[0],
			month: time.value.split("/")[1],
			// userIdXp: JSON.parse(localStorage.getItem("logininfo")).userIdXp
			userIdXp: userId
		});
		// 处理月份
		let m = convertToFullDates(time.value, n.data);
		timeUpload.value.daysWort = m;
		// 可预约的起始时间
		let timeNew = formatDateYMDs(new Date(m[0]));
		timeUpload.value.newDate = timeNew;
		// 获取工作小时
		timNe.value = m[0];
		GetWorkingTime(m[0]);
	};
	// 点击上个月
	const ToptMonth = obj => {
		let year = obj.year;
		let money = dayjs(obj.format).format("MM");
		let times = getPreviousMonthDate(year + "/" + money);
		time.value = times;
		yarnDay();
	};
	// 这个是点击下个月
	const NextMonth = obj => {
		console.log(obj, "1111111111111");
		let year = obj.year;
		let money = dayjs(obj.format).format("MM");
		let times = getNextMonthYearAndMonth(year + "/" + money);
		time.value = times.year + "/" + times.month;
		yarnDay();
		console.log(time, "88888888888888888888888888888888");
	};
	const formatDateYMDs = date => {
		let y = date.getFullYear();
		let m = date.getMonth() + 1;
		let d = date.getDate();
		// 是否补齐0
		// if (props.isCompletionZero) {
		m = m < 10 ? "0" + m : m;
		d = d < 10 ? "0" + d : d;
		// }
		// 年月日拼接符号
		// 默认年月日
		let returnDate = `${y}年${m}月${d}日`;
		return returnDate;
	};
	function getNextMonthYearAndMonth(dateString) {
		var date = new Date(dateString);
		date.setMonth(date.getMonth() + 1);
		var nextMonthYear = date.getFullYear();
		var nextMonthMonth = date.getMonth() + 1;
		return { year: nextMonthYear, month: nextMonthMonth };
	}
	// 上个月份
	function getPreviousMonthDate(dateString) {
		var date = new Date(dateString);
		date.setMonth(date.getMonth() - 1);
		var previousMonthYear = date.getFullYear();
		var previousMonthMonth = date.getMonth() + 1;
		var previousMonthDate = previousMonthYear + "/" + previousMonthMonth.toString().padStart(2, "0");

		return previousMonthDate;
	}
	//转换为天
	function convertToFullDates(dateString, numbersArray) {
		var result = [];

		for (var i = 0; i < numbersArray.length; i++) {
			var month = parseInt(dateString.split("/")[1]); // 提取日期字符串中的月份部分
			var day = numbersArray[i];
			var formattedDay = day.toString().padStart(2, "0"); // 补零格式化天数
			var formattedDate = dateString + "/" + formattedDay;
			result.push(formattedDate);
		}

		return result;
	}
	function generateMonthArray(obj) {
		var start = new Date(obj.startMonth);
		var end = new Date(obj.endMonth);
		var result = [];
		while (start <= end) {
			var year = start.getFullYear();
			var month = start.getMonth() + 1; // 月份从 0 开始，需要加 1
			var formattedMonth = year + "/" + month; // 不补零

			result.push(formattedMonth);
			start.setMonth(start.getMonth() + 1); // 递增一个月
		}

		return result;
	}
	const selectDate = val => {
		if (!calendar.value) return;
		calendar.value.selectDate(val);
	};

	// ------------------------------------------------------------------------------------------------------

	// 这个是当头部导航栏滑倒下面时给tabr加个背景
	const handleScroll = () => {
		const scrollTop = document.documentElement.scrollTop;
		if (scrollTop > 0) {
			statusTab.value = 2;
		} else {
			statusTab.value = 1;
		}
	};
	const parentMethod = num => {
		console.log(num, "5656656565565556");
	};
</script>
<style scoped>
	@import "./index.scss";
	.actBor {
		border: 2px solid #02102e !important;
		border-radius: 8px !important;
	}
</style>
